import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes,asyncRoutes,anyRoutes } from '@/router'
import router from "@/router";

const getDefaultState = ()=>{
  return {
    token: getToken(),
    userInfo:{
      // avatar 用户头像
      avatar:'',
      // 用户名
      name:'',
      // routes 用户允许查看的菜单
      routes:[],
      // 权限按钮组
      buttons:[],
      // 角色列表
      roles:[]
    },
    // 最终的异步路由的结果
    resultAsyncRoutes:[],
    // 最终所有匹配上的路由的结果
    resultRoutes:[]
  }
}

const state = getDefaultState()

// 算出当前用户有权限访问的异步路由
const getResultAsync=(data, routes)=>{
  return routes.filter(item=>{
    if(data.indexOf(item.name)!==-1) {
      if(item.children&&item.children.length) {
        getResultAsync(item.children, routes)
      }
      return true
    }
  })
}

const mutations = {
  // 重置状态
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 设置token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO:(state, user)=>{
    state.userInfo.name = user.name
    state.userInfo.avatar = user.avatar
    state.userInfo.routes = user.routes
    state.userInfo.buttons = user.buttons
    state.userInfo.roles = user.roles
  },
  // 将用户的路由权限信息和当前路由信息进行对比，返回异步路由
  SET_RESULTROUTES:(state,data)=>{
    state.resultAsyncRoutes = getResultAsync(data, asyncRoutes)
    state.resultRoutes = constantRoutes.concat(state.resultAsyncRoutes,anyRoutes)
    router.addRoutes(state.resultRoutes)
  }
}

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let res = await login({username: username.trim(), password: password})
    // code 20000 success
    if (res.code === 20000) {
      commit('SET_TOKEN', res.data.token)
      setToken(res.data.token)
      return Promise.resolve('ok')
    }else {
      return Promise.reject(new Error('fail'))
    }
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    let res = await getInfo(state.token)
    if (res.code === 20000) {
      if (!res.data) {
        return Promise.reject('验证失败，请你重新登录')
      }
      commit('SET_RESULTROUTES',res.data.routes)
      commit('SET_USERINFO', res.data)
    }else {
      return Promise.reject(new Error('fail'))
    }
  },

  // 退出登录
  async logout({ commit, state }) {
    let res = await logout(state.token)
    if(res.code === 20000) {
      removeToken()
      commit('RESET_STATE')
      return Promise.resolve('ok')
    }else {
      return Promise.reject('fail')
    }
  },

  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

